package org.example.algorithm.stack;

import java.util.Stack;

public class MinStackSolution2 {
    private Stack<Long> stack;
    private int min;

    public MinStackSolution2() {
        this.stack = new Stack<>();
    }

    public void push(int val) {
        if (this.stack.isEmpty()) {
            stack.push(0L);
            min = val;
            return;
        }
        long diff = val - min;
        if (diff >= 0) {
            stack.push((long) diff);
            return;
        }
        min = val;
        stack.push((long) diff);
    }

    public void pop() {
        Long val = stack.pop();
        if (val >= 0) {
            return;
        }
        min -= val;
    }

    public int top() {
        Long val = stack.peek();
        if (val >= 0) {
            return Math.toIntExact(val+min);
        }
        return Math.toIntExact(min);
    }

    public int getMin() {
        return Math.toIntExact(this.min);
    }
}
